package lazy.libs.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 文件工具
 * 
 * @author gong
 * 
 */
public class HtmlFileUtil {

	/**
	 * 将远程文件转换为StringBuffer
	 * 
	 * @return
	 * @throws IOException
	 * @throws MalformedURLException
	 */
	public static StringBuffer downloadAsStringBuffer(String url) throws MalformedURLException, IOException {
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();

			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.4)");
			conn.setRequestMethod("GET");
			HttpURLConnection.setFollowRedirects(true);

			conn.connect();
			return readAsStringBuffer(conn.getInputStream());
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
	}

	public static StringBuffer readAsStringBuffer(InputStream is) throws IOException {
		StringBuffer sb = null;

		BufferedInputStream bis = null;
		BufferedReader br = null;

		try {
			sb = new StringBuffer();
			bis = new BufferedInputStream(is);
			br = new BufferedReader(new InputStreamReader(bis));
			String line = br.readLine();
			int size = 0;
			while (line != null) {
				size += line.getBytes().length;
				sb.append(line).append("\n");
				line = br.readLine();
			}

		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} finally {
				try {
					if (bis != null) {
						bis.close();
					}
				} finally {
					if (is != null) {
						is.close();
					}
				}
			}
		}
		return sb;
	}
}